import React, { useEffect, useRef, useState } from 'react'
import styles from './index.module.less'
import { Button, Form, Input, Picker, SafeArea, Toast } from 'antd-mobile'
import { AddCircleOutline, CloseCircleFill } from 'antd-mobile-icons'
import { getData, postData, postFile } from '@/servers/http'
import { api } from '@/servers/api'
import { history } from 'umi'
import wx from 'weixin-webview-jssdk'

const Fill = () => {
    const { id, domain } = history.location.query || {}
    const [form] = Form.useForm()
    // 学员类型下拉
    const [stuTypeList, setStuTypeList] = useState([])
    // 文化程度下拉
    const [degreeList, setDegreeList] = useState([])
    // 报名文件列表
    const [fileList, setFileList] = useState<any[]>([])
    const fileRef = useRef<any>(null)
    /** 获取学员类型下拉列表 */
    const getStudentTypeList = () => {
        getData(api.studentCategory, { mlh_side_domain: domain }).then(({ status, data }) => {
            if (status === 200) {
                const stuArr = data?.map((item: { id: number; name: string }) => ({ label: item.name, value: item.id })) || []
                setStuTypeList(stuArr)
            }
        })
    }
    /** 获取文化程度下拉列表 */
    const getDegreeList = () => {
        getData(api.degreeCategory, { code: 'STUDENT_DEGREE', mlh_side_domain: domain }).then(({ status, data }) => {
            if (status === 200) {
                const degreeArr = data?.map((item: string) => ({ label: item, value: item })) || []
                setDegreeList(degreeArr || [])
            }
        })
    }
    useEffect(() => {
        document.title = '机构报名'
        getStudentTypeList()
        getDegreeList()
    }, [])
    /** 上传文件 */
    const upLoadImage = (e: any) => {
        if (e.target?.files?.length > 0) {
            if (e.target.files.length + fileList.length > 5) {
                Toast.show('最多上传五份文件')
                return
            }
            const promiseArr: any[] = []
            e.target?.files?.forEach((file: File) => {
                promiseArr.push(postFile(api.mlhUpload, { file, mlh_side_domain: domain }))
            })
            const toast = Toast.show({
                icon: 'loading',
                content: '上传中…',
                duration: 0,
            })
            Promise.allSettled(promiseArr)
                .then(res => {
                    const fileData: { address: string; name: string }[] = [...fileList]
                    res.forEach(item => {
                        if (item.status === 'fulfilled') {
                            const { filename, url } = item.value.data || {}
                            fileData.push({ address: url, name: filename })
                        }
                    })
                    setFileList(fileData)
                    form.setFieldValue('credit_files', fileData)
                    toast.close()
                })
                .catch(() => {
                    toast.close()
                })
        }
    }
    /** 下载模板文件 */
    const downloadFile = () => {
        const data = { url: 'https://cp-oss.busionline.com/static/%E5%AD%A6%E5%91%98%E7%99%BB%E8%AE%B0%E8%A1%A8.docx', name: '学员登记表.docx' }
        wx.miniProgram.navigateTo({
            url: `/pageStudent/pages/download/index?type=download&data=${encodeURIComponent(JSON.stringify(data))}`,
        })
    }
    /** 移除文件 */
    const removeFile = (address: string) => {
        const newArr = fileList.filter(item => item.address !== address)
        setFileList(newArr)
        form.setFieldValue('credit_files', newArr)
    }
    /** 提交 */
    const handleOk = () => {
        form.validateFields().then(values => {
            const { cate_id, degree } = values || {}
            const params = {
                ...values,
                cate_id: cate_id[0],
                degree: degree[0],
                mlh_side_domain: domain,
            }
            postData(`${api.companyEnroll}/${id}`, params).then(({ status }) => {
                if (status === 200) {
                    Toast.show('报名成功')
                    history.replace(`/organization/detail?id=${id}&domain=${domain}`)
                }
            })
        })
    }

    return (
        <div className={styles.organization_fill}>
            <img className={styles.bg_head} src="http://chuangpei-prod.oss.busionline.com/wechat/asserts/image/bg_org_detail@2x.png" />
            <div className={styles.form_box}>
                <p className={styles.title}>学员报名</p>
                <Form form={form} layout="horizontal">
                    <Form.Item label="姓名" name="realname" rules={[{ required: true }]}>
                        <Input placeholder="请输入" />
                    </Form.Item>
                    <Form.Item label="身份证" name="idcard" rules={[{ required: true }]}>
                        <Input placeholder="请输入" />
                    </Form.Item>
                    <Form.Item
                        label="学员类型"
                        name="cate_id"
                        trigger="onConfirm"
                        rules={[{ required: true }]}
                        onClick={(e, pickerRef) => {
                            pickerRef.current?.open()
                        }}
                    >
                        <Picker columns={[stuTypeList]}>
                            {value => {
                                return value[0] ? value[0].label : <text className={styles.placeholder}>请选择</text>
                            }}
                        </Picker>
                    </Form.Item>
                    <Form.Item label="手机号码" name="phone" rules={[{ required: true }]}>
                        <Input placeholder="请输入" type="number" />
                    </Form.Item>
                    <Form.Item
                        label="文化程度"
                        name="degree"
                        trigger="onConfirm"
                        rules={[{ required: true }]}
                        onClick={(e, pickerRef) => {
                            pickerRef.current?.open()
                        }}
                    >
                        <Picker columns={[degreeList]}>
                            {value => {
                                return value[0] ? value[0].label : <text className={styles.placeholder}>请选择</text>
                            }}
                        </Picker>
                    </Form.Item>
                    <Form.Item label="毕业院校" name="college">
                        <Input placeholder="请输入" />
                    </Form.Item>
                    <Form.Item label="专业" name="major">
                        <Input placeholder="请输入" />
                    </Form.Item>
                    <Form.Item label="其他证件" name="card_name">
                        <Input placeholder="请输入" />
                    </Form.Item>
                    <Form.Item label="证件号码" name="card_number">
                        <Input placeholder="请输入" />
                    </Form.Item>
                    <Form.Item label="报名材料" name="fake_field" childElementPosition="right" required>
                        <AddCircleOutline color="rgba(23,26,29,0.4)" fontSize={21} onClick={() => fileRef.current?.click()} />
                        <input ref={fileRef} type="file" multiple onChange={upLoadImage} style={{ display: 'none', cursor: 'pointer' }} />
                    </Form.Item>
                    <Form.Item name="credit_files" rules={[{ required: true, message: '请上传报名材料' }]}>
                        <div className={styles.credit_box}>
                            <p className={styles.extra_title}>可上传报名资料，格式为pdf、docx、xlsx、pptx、jpg，jpeg，png文件，最多上传5份</p>
                            <Button className={styles.download} fill="none" onClick={downloadFile}>
                                下载报名表模板
                            </Button>
                            <p className={styles.download_tip}>请下载报名表模板填写后再进行上传</p>
                            {fileList.map(item => {
                                const { address, name } = item || {}
                                return (
                                    <div className={styles.file_box} key={address}>
                                        <img src="http://chuangpei-prod.oss.busionline.com/qzsx/file_img.png" />
                                        <div className={styles.file_content}>
                                            <p className={styles.file_text}>{name}</p>
                                            <CloseCircleFill className={styles.remove_icon} onClick={() => removeFile(address)} />
                                        </div>
                                    </div>
                                )
                            })}
                        </div>
                    </Form.Item>
                </Form>
            </div>
            <SafeArea position="bottom" />
            <div className={styles.footer_box}>
                <Button className={styles.btn} onClick={handleOk}>
                    提交
                </Button>
                <SafeArea position="bottom" />
            </div>
        </div>
    )
}

export default Fill
